package com.group.flagtivities;

import java.lang.ref.WeakReference;

import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.util.DisplayMetrics;
import android.widget.TextView;

public class BitmapDownloaderTask extends AsyncTask<String, Void, Bitmap> {
	private DisplayMetrics metrics;
	private final WeakReference<TextView> textViewReference;
	
	public BitmapDownloaderTask(TextView textView, DisplayMetrics metrics) {
		textViewReference = new WeakReference<TextView>(textView);
		this.metrics = metrics;
	}
	
	@Override
	protected Bitmap doInBackground(String[] params) {
		return ImageUtil.downloadBitmap(params[0]);
	}
	
	@Override
	protected void onPostExecute(Bitmap bitmap) {
		if (isCancelled()) {
			bitmap = null;
		}
		
		if (textViewReference != null) {
			TextView textView = textViewReference.get();
			if (textView != null && bitmap != null) {
				BitmapDrawable drawable = ImageUtil.cropImage(new BitmapDrawable(bitmap), 40, metrics);
				drawable.setBounds(0, 0, 40, 40);
				textView.setCompoundDrawablesWithIntrinsicBounds(drawable, null, null, null);
	        	textView.setCompoundDrawablePadding(10);
			}
		}
	}
}
